/*
 * 文件名： CheckOrderCiticExPayImpl.java
 * 
 * 工程名称: checkorder-service
 *
 * Gopay
 *
 * 创建日期： 2016年7月8日
 *
 * Copyright(C) 2016, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.checkorder.service.impl.expay;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.CiticConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.citic.expay.CiticExpay;
import com.gopay.common.domain.bank.citic.expay.CiticExpayErrorMessage;
import com.gopay.common.domain.bank.citic.expay.CiticExpayResMessage;
import com.gopay.common.domain.bank.citic.expay.query.CiticExpayQueryResMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.TransUtil;
import com.gopay.remote.bank.ExPayInteractRemoteService;

/**
 * 中信银行快捷支付对单操作类
 *
 * @author 宣广海
 *
 * @version
 *
 * @since 2016年7月8日
 */
public class CheckOrderCiticExPayImpl implements BankOrderService {

    private final static Logger logger = LoggerFactory.getLogger("CITIC");

    /**
     * 注入对象
     */
    @Resource(name = "bankExPayClient")
    private ExPayInteractRemoteService bankExPayClient;

    @Override
    public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
        /**
         * 定义返回对象
         */
        CheckOrderResult checkOrderResult = new CheckOrderResult();
        checkOrderResult.setSuccess(false);
        checkOrderResult.setOrderId(bankOrder.getOrderId());

        CiticExpay citicExpay = new CiticExpay();

        citicExpay.setOrderId(bankOrder.getOrderId()); // 国付宝系统订单号
        citicExpay.setBankOrderId(bankOrder.getOutOrderId());
        citicExpay.setBank(bankOrder.getBankCode());
        citicExpay.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
        citicExpay.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
        citicExpay.setOrderDate(DateUtils.format(bankOrder.getSendBankTm(), "yyyyMMdd HH:mm:ss"));

        Result result = new Result();
        try {

            // 如果是退款订单赋值原银行订单号
            if (BisBankBusinessProd._12.value.equals(bankOrder.getBankBizProdCode())) {
                citicExpay.setTkOriBankOrderId(bankOrder.getOriOutOrderId());
            }

            /**
             * 调用中信银行快捷支付单笔订单查询接口
             */
            result = bankExPayClient.queryOrder(citicExpay);
            if(StringUtils.isNotBlank(result.getBankRetCode())){
                //add by liuyu, 20170803, 快捷API失败通知
                bankOrder.setBankRespCode(result.getBankRetCode());
            }

            if (!result.isSuccess()) {
                logger.error("bankExPayClient.queryOrder fail.");

                if (ProcCodeConstants.PROC_CODE_100E6058.equals(result.getResultCode())) {
                    BankCountDownLatch.failIncrease(bankOrder.getBankCode());
                }
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
                checkOrderResult.setErrMsg("系统返回对账结果为空");
                return checkOrderResult;
            }

            CiticExpayResMessage resMsg = (CiticExpayResMessage) result.getDefaultModel();
            if (null == resMsg) {
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
                checkOrderResult.setErrMsg("系统返回对账结果为空");
                return checkOrderResult;
            }
            // 查询结果
            CiticExpayQueryResMessage queryResMessage = resMsg.getExpayMessage().getQueryResMessage();
            // 异常结果
            CiticExpayErrorMessage errorMsg = resMsg.getExpayMessage().getErrorMessage();
            if (BisBankBusinessProd._12.value.equals(bankOrder.getBankBizProdCode()) && null != errorMsg
                    && "0401".equals(errorMsg.getRetCode())) {
                // 原支付流水不存在
                logger.info("退款订单 orderId:" + bankOrder.getOrderId() + ",retMsg:" + errorMsg.getRetMsg());
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5041);
                checkOrderResult.setErrMsg("银行返回退款交易不存在.");
                return checkOrderResult;

            } else if (null != errorMsg) {

                logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:"
                        + ProcCodeConstants.PROC_CODE_100E6022 + " errMsg:" + errorMsg.getRetMsg());
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
                checkOrderResult.setErrMsg("银行返回对账结果为空");
                return checkOrderResult;
            } else {
                /**
                 * 0-成功(查询成功)
                 */
                if (CiticConstants.EXPAY_QUERY_RECODE_SUCCESS.equals(queryResMessage.getRetCode())) {
                    /**
                     * 如果查询成功，则一定有定单信息
                     */
                    if (CiticConstants.EXPAY_QUERY_STATUS_SUCCESS.equals(queryResMessage.getStatus())) {
                        /**
                         * 查询成功
                         */
                        logger.error(
                                "中信快捷订单:" + bankOrder.getOrderId() + "交易状态为：" + queryResMessage.getStatus() + "，查询成功");
                        checkOrderResult.setSuccess(true);
                        InAccInfo accInfo = new InAccInfo();
                        accInfo.setOrderId(bankOrder.getOrderId());
                        /**
                         * 报文返回金额精确到分
                         */
                        String amount = TransUtil.amountConvert2Yuan(queryResMessage.getAmount());
                        accInfo.setAmount(new BigDecimal(amount));
                        accInfo.setRetCode("00");
                        accInfo.setCardType(BankCardType.Unknown.toString());
                        checkOrderResult.setAccInfo(accInfo);
                    } else if (CiticConstants.EXPAY_QUERY_STATUS_DEALING.equals(queryResMessage.getStatus())) {
                        /**
                         * 处理中
                         */
                        logger.error("中信快捷订单:" + bankOrder.getOrderId() + "交易状态为:" + queryResMessage.getStatus()
                                + "，银行返回处理中.");
                        checkOrderResult.setErrMsg("银行返回处理中");
                    }

                    else if (CiticConstants.EXPAY_QUERY_STATUS_FAILED.equals(queryResMessage.getStatus())) {
                        /**
                         * 失败
                         */
                        InAccInfo accInfo = new InAccInfo();
                        accInfo.setOrderId(bankOrder.getOrderId());
                        /**
                         * 报文返回金额精确到分
                         */
                        String amount = TransUtil.amountConvert2Yuan(queryResMessage.getAmount());
                        accInfo.setAmount(new BigDecimal(amount));
                        accInfo.setRetCode("01");
                        accInfo.setCardType(BankCardType.Unknown.toString());
                        checkOrderResult.setAccInfo(accInfo);
                        checkOrderResult.setBankFailure(true);
                        logger.error(
                                "中信快捷订单:" + bankOrder.getOrderId() + "交易状态为:" + queryResMessage.getStatus() + "，失败.");
                        checkOrderResult.setErrMsg("银行返回失败.");
                    } else {
                        /**
                         * 处理中
                         */
                        logger.error("中信快捷订单:" + bankOrder.getOrderId() + "交易状态为:" + queryResMessage.getStatus()
                                + "，银行返回处理中.");
                        checkOrderResult.setErrMsg("银行返回处理中");
                    }
                } else {
                    /**
                     * 处理中
                     */
                    logger.error(
                            "中信快捷订单:" + bankOrder.getOrderId() + "返回码为:" + queryResMessage.getRetCode() + "，查询失败.");
                    checkOrderResult.setErrMsg("银行返回处理中");
                }

            }
            return checkOrderResult;
        } catch (Exception e) {
            logger.error(bankOrder.getOrderId() + ": bankExPayClient.queryOrder() fail.", e);
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
            checkOrderResult.setErrMsg("中信快捷对账异常。");
            return checkOrderResult;
        }

    }

    @Override
    public BankOrder getDbOrder() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public BaseMessage dayend(String bank_bus) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result getDayendMsg(String string) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<CheckOrderResult> checkDayend(String bank_bus) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
        // TODO Auto-generated method stub
        return null;
    }

}
